# -*- coding: utf-8 -*-
# __author__ = "Zok"
# Date: 2018/6/9

import socket
import struct
import json
from conf import setting
from core.public import Print


# 服务器sever类
class FTPSever:
    # 从配置文件中获取 类的属性
    address_family = setting.sever_conf.get('address_family')
    socket_type = setting.sever_conf.get('socket_type')
    allow_reuse_address = setting.sever_conf.get('allow_reuse_address')
    packet_size = setting.sever_conf.get('packet_size')
    coding = setting.sever_conf.get('coding')
    listen = setting.sever_conf.get('listen')

    def __init__(self, sever_address, bind_and_activate=True):
        self.sever_address = sever_address  # 元祖形式参数
        self.bind_and_activate = bind_and_activate  # 是否绑定并激活，默认真
        self.soc = socket.socket(self.address_family, self.socket_type)  # 创建socket对象
        if bind_and_activate:
                self.sever_bind()
                self.sever_listen()

    def sever_bind(self):
        """
        绑定IP\端口
        :return:
        """
        if self.allow_reuse_address:
            self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.soc.bind(self.sever_address)

    def sever_listen(self):
        """
        设置最大监听数量
        :return:
        """
        self.soc.listen(self.listen)

    def sever_close(self):
        """
        关闭创建的socket对象
        :return:
        """
        self.soc.close()

    def get_request(self):
        """
        获取请求链接服务器对象
        :return: 返回获取到的对象，元祖形式
        """
        return self.soc.accept()

    def put(self):
        pass

    def run(self):
        Print.green('启动成功...')
        while True:
            self.conn, self.client_addr= self.get_request()
            Print.green('客户连接 %s' % self.client_addr)
            while True:
                try:
                    # 获取包头 长
                    heard_size = struct.unpack(self.conn.recv(4))[0]
                    if not heard_size:  # linux系统断开链接
                        break

                    # 获取包头  内容json
                    heard_json = self.conn.recv(heard_size).decode(self.coding)

                    # 包头信息  转为能用的dict
                    heard_dict = json.loads(heard_json)

                    # 取包内容 类型   判断是输入的下载、上传、切换目录命令
                    get_type = heard_dict.get('total_type')

                    heard_dict.get('total_size')

                    Print.blue('用户输入命令类型：%s' % get_type)

                except ConnectionResetError:  # windows 系统断开链接
                    Print.red('客户断开链接 %s' % self.client_addr)
